<?php
namespace App\Services\Register\Register;

use App\Models\Agent\Agent;
use App\Models\Agent\Software;
use App\Models\Register\Register;
use App\Models\User\Users;
use Illuminate\Hashing\BcryptHasher;
use DB;

class RegisterLogic
{
    // 注册
    /**
     * @param $data
     * @return array
     */
    public function register($data)
    {
        $redis = app('redis');
        $rcode = $redis->get($data['phone']);
        if($data['code'] != $rcode){
            return verify_err(null, '验证码错误');
        }
        unset($data['validate']);
        unset($data['token']);
        unset($data['code']);
        $data['create_at'] = date("Y-m-d H:i:s", time());
        $data['user_name'] = $data['phone'];
        $data['password'] = (new BcryptHasher())->make($data['phone']);
        if(!empty($data['software_id'])){
            //判断代理状态决定用户来源
            $res = Agent::select('status','simple_name')->where('software_id', '=', $data['software_id'])->first()->toArray();
            $data['come_from'] = $res['simple_name'];
            if($res['status']!=2){
                $data['software_id'] = '';
                $data['come_from'] = '';
            }
        }
        //初始化users表
        DB::beginTransaction();
        try {
            $rst = Register::insertGetId($data);
            $usersData = [
                'info_id' => $rst,
                'uuid' => rand_string(32),
            ];
            $rst1 = Users::insert($usersData);
        } catch (\Exception $e) {
            DB::rollBack();
            return auto_failure($e->getMessage());
        }
        if ($rst && $rst1) {
            DB::commit();
            return auto_return(['id' => $rst],'添加成功！');
        } else {
            DB::rollBack();
            return auto_failure('添加失败');
        }
    }

    // 编辑
    public function edit($data)
    {
        unset($data['token']);
        $res = Register::where('id', $data['id'])->update($data);
        return auto_return($res,'成功!');
    }
}
